package k8s

import (
	"context"
	"fmt"
	"goproject/api/v1alpha1"
	"goproject/logger"
	"goproject/util"
	"strings"
	"time"
)

// GenerateChaosName 生成CRD资源名称
// a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.',
// and must start and end with an alphanumeric character
// (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')
func GenerateChaosName(aimName string, resource string) string {
	return fmt.Sprintf("%s.%s.%s", time.Now().Format("d01-02t15-04-05.000000"),
		aimName, strings.ToLower(resource))
}

func InjectChaos(chaos v1alpha1.InnerObject) {
	log := logger.GetLogger()
	// 断言，必须确实是 Chaos Mesh 对象
	if chaos.GetObjectKind().GroupVersionKind().GroupVersion() != v1alpha1.GroupVersion {
		log.Panicf("注入的对象不是 Chaos Mesh 对象，而是 %s", chaos.GetObjectKind().GroupVersionKind().GroupVersion())
	}
	log.Debugf("注入 %s 类型故障 %s", chaos.GetObjectKind().GroupVersionKind().Kind, chaos.GetName())
	// 注入
	err := util.RetryWithDefaultTimeoutAndInterval(func() error {
		err := chaosMesh.Post().
			Namespace(util.ChaosMeshObjectNamespace).
			Resource(chaos.GetObjectKind().GroupVersionKind().Kind).
			Body(chaos).Do(context.TODO()).Into(chaos)
		if err != nil {
			log.Warnf("故障 %s 注入错误 %s 将重试: %v", chaos.GetName(), err.Error(), chaos)
			return err
		}
		return nil
	})
	if err != nil {
		log.Panicf("RetryWithDefaultTimeoutAndInterval 故障 %s 注入失败: %v, 故障内容: %v", chaos.GetName(), err, chaos)
	}
}
